import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


img_dir = '../../../../../large_data/CV2/lesson/Day06'
img_name = 'hammer.jpg'
# img_dir = '../../../../../large_data/pic'
# img_name = 'DSC05039.JPG'
# img_name = 'DSC05022_1.JPG'
# img_name = 'dog.jpg'
# img_name = 'dog_bird.jpg'
img_path = os.path.join(img_dir, img_name)

spr = 2
spc = 4
spn = 0
plt.figure(figsize=[14, 10])

sep('load')
img = cv.imread(img_path, cv.IMREAD_GRAYSCALE)
# img = cv.resize(img, None, fx=0.1, fy=0.1, interpolation=cv.INTER_CUBIC)
print('original shape', img.shape)
H, W = img.shape
H2 = (H - 1) // 2
W2 = (W - 1) // 2
my_show_img(img, 'original', cmap='gray')
img_color = cv.cvtColor(img, cv.COLOR_GRAY2BGR)

sep('bin')
ret, bin = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
print_numpy_ndarray_info(bin, 'bin')
my_show_img(bin, 'bin', cmap='gray')

sep('contours')
contours, hierarchy = cv.findContours(bin, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
print(contours)
sys.exit(0)

bg = np.zeros((*bin.shape, 3), dtype=np.uint8)
bg_ = bg.copy()
cv.drawContours(bg, contours, -1, (0, 255, 0), 2)
print('n_contours:', len(contours))
my_show_img(bg, 'contours', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

sep('largest contour')
area_max = 0
con_i = 0
for i, c in enumerate(contours):
    area = cv.contourArea(c)
    if area > area_max:
        area_max = area
        con_i = i
print(i)
bg = bg_.copy()
con = contours[con_i]
cv.drawContours(bg, [con], 0, (0, 255, 0), 2)
my_show_img(bg, 'largest contour', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

sep('min rect')
rotated_rect = cv.minAreaRect(con)
pts = cv.boxPoints(rotated_rect)
pts = np.int32(pts)
print(pts)
pts = np.expand_dims(pts, (0, 1))
print(pts)
print_numpy_ndarray_info(pts, 'pts')
cv.polylines(img_color, pts, True, (0, 255, 0), 2)
my_show_img(img_color, 'min rect', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

plt.show()
